package cn.easyplatform.studio.web.controller;

import cn.easyplatform.entities.beans.project.ProjectBean;
import cn.easyplatform.lang.Strings;
import cn.easyplatform.studio.StudioApp;
import cn.easyplatform.studio.cmd.identity.GetSMSCmd;
import cn.easyplatform.studio.cmd.identity.GetStudioProjectCmd;
import cn.easyplatform.studio.cmd.identity.GetStudioUserCmd;
import cn.easyplatform.studio.cmd.identity.RegisterCmd;
import cn.easyplatform.studio.context.Contexts;
import cn.easyplatform.studio.utils.StringUtil;
import cn.easyplatform.studio.utils.WebUtils;
import cn.easyplatform.studio.vos.InviteVo;
import cn.easyplatform.studio.vos.LoginUserVo;
import cn.easyplatform.studio.vos.SMSVo;
import org.zkoss.util.resource.Labels;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.Page;
import org.zkoss.zk.ui.WrongValueException;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zk.ui.metainfo.ComponentInfo;
import org.zkoss.zk.ui.util.Composer;
import org.zkoss.zk.ui.util.ComposerExt;
import org.zkoss.zul.*;
import org.zkoss.zul.theme.Themes;

public class RegisterController implements Composer<Component>, ComposerExt<Component>, EventListener<Event> {

    private Component submit;

    private Textbox mobile;

    private Textbox verification;

    private Textbox name;

    private Textbox password;

    private Textbox doublePassword;

    private Component parentComponent;

    private Timer timer;

    private A verificationA;

    private int count = 60;

    private InviteVo inviteVo;
    @Override
    public void onEvent(Event event) throws Exception {
        if (event.getTarget().equals(timer)) {
            count--;
            if (count > 0) {
                verificationA.setLabel(count + "s");
                verificationA.setDisabled(true);
            } else {
                timer.stop();
                verificationA.setLabel(Labels.getLabel("register.verification.get"));
                verificationA.setDisabled(false);
                count = 60;
            }

        } else if ("register_verification_a".equals(event.getTarget().getId())) {
            if (Strings.isBlank(mobile.getText()) ||
                    StringUtil.regexString(mobile.getText(), StringUtil.RegexType.RegexIsMobile) == false)
                throw new WrongValueException(mobile, Labels
                        .getLabel("register.phone.placeholder"));
            Boolean isSuccess = StudioApp.execute(new GetSMSCmd(mobile.getText(), SMSVo.SMSType.SMSRegister));
            if (isSuccess == true) {
                timer = new Timer();
                timer.setDelay(1000);
                event.getTarget().getParent().appendChild(timer);
                timer.addEventListener(Events.ON_TIMER, this);
                timer.setRepeats(true);
                timer.start();
            }
        } else if ("register_login".equals(event.getTarget().getId())) {
            Contexts.setInvite(inviteVo);
            Include include = (Include) parentComponent.getRoot();
            include.setSrc("~./include/login/login1.zul");
        } else if ("register_forget".equals(event.getTarget().getId())) {
            Include include = (Include) parentComponent.getRoot();
            include.setSrc("~./include/retrievePassword/retrievePassword1.zul");
        } else if ("register_submit".equals(event.getTarget().getId())) {
            if (Strings.isBlank(mobile.getText()) ||
                    StringUtil.regexString(mobile.getText(), StringUtil.RegexType.RegexIsMobile) == false)
                throw new WrongValueException(mobile, Labels
                        .getLabel("register.phone.placeholder"));
            if (Strings.isBlank(verification.getText()) ||
                    StringUtil.regexString(verification.getText(), StringUtil.RegexType.RegexIsVerification) == false)
                throw new WrongValueException(verification, Labels
                        .getLabel("register.verification.input.placeholder"));
            if (Strings.isBlank(name.getText()) ||
                    StringUtil.regexString(name.getText(), StringUtil.RegexType.RegexIsName) == false)
                throw new WrongValueException(name, Labels
                        .getLabel("constraint.name"));
            if (Strings.isBlank(password.getText()) ||
                    StringUtil.regexString(password.getText(), StringUtil.RegexType.RegexIsPassword) == false)
                throw new WrongValueException(password, Labels
                        .getLabel("constraint.password"));
            if (Strings.isBlank(doublePassword.getText()) ||
                    StringUtil.regexString(doublePassword.getText(), StringUtil.RegexType.RegexIsPassword) == false)
                throw new WrongValueException(doublePassword, Labels
                        .getLabel("constraint.password"));
            if (password.getText().equals(doublePassword.getText()) == false)
                throw new WrongValueException(doublePassword, Labels
                        .getLabel("constraint.no.equal.password"));

            Boolean isSuccess = StudioApp.execute(new RegisterCmd(
                    mobile.getText().trim(), name.getText().trim(), password.getText().trim(), verification.getText().trim()));
            if (isSuccess == true) {
                /*WebUtils.showSuccess(Labels.getLabel("register.finish.login"));
                Include include = (Include) parentComponent.getRoot();
                include.setSrc("~./include/login/login1.zul");*/
                LoginController loginController = new LoginController();
                loginController.login(event.getTarget(), mobile, password, parentComponent, inviteVo);
            }
        }
    }

    @Override
    public void doAfterCompose(Component component) throws Exception {
        inviteVo = Contexts.getInvite();
        Label titleLabel = (Label) component.query("#register_title");
        if (inviteVo != null) {
            LoginUserVo userVo = StudioApp.execute(new GetStudioUserCmd(inviteVo.getUserID()));
            ProjectBean projectBean = StudioApp.execute(new GetStudioProjectCmd(inviteVo.getProjectID()));
            titleLabel.setValue(Labels.getLabel("product.invite.title",
                    new Object[] {" " +userVo.getName()+" " , " " +projectBean.getName()+" "}));
        } else {
            titleLabel.setValue(Labels.getLabel("register.title"));
        }
        Contexts.setInvite(null);
        parentComponent = component;
        submit = component.query("#register_submit");
        submit.addEventListener(Events.ON_CLICK, this);

        mobile = (Textbox) component.query("#register_mobile");
        verification = (Textbox) component.query("#register_verification");
        name = (Textbox) component.query("#register_name");
        password = (Textbox) component.query("#register_password");
        doublePassword = (Textbox) component.query("#register_password_double");

        StringBuilder sb = new StringBuilder();
        sb.append("if(this.getValue()!=''){var wgt=web.Widget.$('")
                .append(verification.getUuid()).append("');wgt.fire('onClick');}");
        sb.append("else this.setErrorMessage('")
                .append(Labels.getLabel("register.phone.placeholder"))
                .append("')");
        mobile.setWidgetListener(Events.ON_OK, sb.toString());
        mobile.setWidgetListener(
                Events.ON_OK,
                "if(jq(zk.$('$" +mobile.getId() +"')).val().length!=0){jq(zk.$('$" +verification.getId() +"')).focus();}");

        sb.setLength(0);
        sb.append("if(this.getValue()!=''){var wgt=web.Widget.$('")
                .append(name.getUuid()).append("');wgt.fire('onClick');}");
        sb.append("else this.setErrorMessage('")
                .append(Labels.getLabel("register.verification.input.placeholder"))
                .append("')");
        verification.setWidgetListener(Events.ON_OK, sb.toString());
        verification.setWidgetListener(
                Events.ON_OK,
                "if(jq(zk.$('$" +verification.getId() +"')).val().length!=0){jq(zk.$('$" +name.getId() +"')).focus();}");

        sb.setLength(0);
        sb.append("if(this.getValue()!=''){var wgt=web.Widget.$('")
                .append(password.getUuid()).append("');wgt.fire('onClick');}");
        sb.append("else this.setErrorMessage('")
                .append(Labels.getLabel("constraint.name"))
                .append("')");
        name.setWidgetListener(Events.ON_OK, sb.toString());
        name.setWidgetListener(
                Events.ON_OK,
                "if(jq(zk.$('$" +name.getId() +"')).val().length!=0){jq(zk.$('$" +password.getId() +"')).focus();}");

        sb.setLength(0);
        sb.append("if(this.getValue()!=''){var wgt=web.Widget.$('")
                .append(doublePassword.getUuid()).append("');wgt.fire('onClick');}");
        sb.append("else this.setErrorMessage('")
                .append(Labels.getLabel("constraint.password"))
                .append("')");
        password.setWidgetListener(Events.ON_OK, sb.toString());
        password.setWidgetListener(
                Events.ON_OK,
                "if(jq(zk.$('$" +password.getId() +"')).val().length!=0){jq(zk.$('$" +doublePassword.getId() +"')).focus();}");

        sb.setLength(0);
        sb.append("if(this.getValue()!=''){var wgt=web.Widget.$('")
                .append(submit.getUuid()).append("');wgt.fire('onClick');}");
        sb.append("else this.setErrorMessage('")
                .append(Labels.getLabel("constraint.password"))
                .append("')");
        doublePassword.setWidgetListener(Events.ON_OK, sb.toString());
        doublePassword.setWidgetListener(
                Events.ON_OK,
                "if(jq(zk.$('$" +doublePassword.getId() +"')).val().length!=0){jq(zk.$('$" +submit.getId() +"')).focus();}");

        verificationA = (A) component.query("#register_verification_a");
        verificationA.addEventListener(Events.ON_CLICK, this);
        component.query("#register_login").addEventListener(Events.ON_CLICK, this);
        if (inviteVo != null)
            component.query("#register_forget").setVisible(false);
        else
            component.query("#register_forget").setVisible(true);
        component.query("#register_forget").addEventListener(Events.ON_CLICK, this);
    }

    @Override
    public ComponentInfo doBeforeCompose(Page page, Component component, ComponentInfo componentInfo) throws Exception {
        Themes.setTheme(Executions.getCurrent(), "atrovirens_c");
        component.addEventListener(Events.ON_OK, new EventListener<Event>() {
            @Override
            public void onEvent(Event event) throws Exception {
                Events.postEvent(new Event(Events.ON_CLICK, submit));
            }
        });
        return componentInfo;
    }

    @Override
    public void doBeforeComposeChildren(Component component) throws Exception {

    }

    @Override
    public boolean doCatch(Throwable throwable) throws Exception {
        return false;
    }

    @Override
    public void doFinally() throws Exception {

    }
}
